<?php

/**
 * This file is part of the Pagizer package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright   Copyright (c) 2010 Advisa (http://www.advisa.fr)
 * @author      Pagizer Core Team <team@pagizer.org>
 * @package     pagizer
 * @subpackage  website
 */

class m_website_actions_AjaxSwitchPageStatusAction extends m_backoffice_extends_Action
{
    var $conflictPage;

    public function execute()
    {
        $docId = $this->getRequestParameter('docId');
        $docLang = $this->getRequestParameter('docLang');       

        if(!is_null($docId) && !is_null($docLang))
        {
            $tempDocService = m_backoffice_services_TempDocService::getInstance();
            
            $page = f_document_Provider::getInstance()->getByModelAndUniqueId('website/Page', $docId, $docLang);

            if($page->getPublicationStatus() == 'DRAFT')
            {
                // Check if url 
                if($this->checkUrl($page))
                {
                    return '&pageId='.$this->conflictPage->getUniqueId().'&pageLang='.$this->conflictPage->getLang();
                }
                else
                {
                    $page->setPublicationStatus('PUBLISHED')->save(false);
                    if($tempDocService->hasTemporary($docId, $docLang))
                    {
                        $tempDoc = $tempDocService->getTemporaryDocument($docId, $docLang);
                        $tempDoc->setPublicationStatus('PUBLISHED');
                        $tempDocService->saveTemporaryDocument($tempDoc);
                    }
                    return 'success';
                }
            }
            else
            {
                    $page->setPublicationStatus('DRAFT')->save(false);
                    if($tempDocService->hasTemporary($docId, $docLang))
                    {
                        $tempDoc = $tempDocService->getTemporaryDocument($docId, $docLang);
                        $tempDoc->setPublicationStatus('DRAFT');
                        $tempDocService->saveTemporaryDocument($tempDoc);
                    }
                    return 'success';
            }
        }
    }

	/**
	 * Check if url exist
	 * @return boolean
	 */
	private function checkUrl($page)
	{
        $this->conflictPage =    $this->getDocumentProvider()->loadDocuments("modules_website/Page")
                            ->whereIsEqual("document_publicationstatus", "PUBLISHED")
                            ->whereIsEqual("url", $page->getUrl())
                            ->whereIsEqual("websiteId", $page->getWebsiteId())
                            ->retrieveFirstDocument($page->getLang());

        return count($this->conflictPage) > 0;
	}
}
